<template>
  <div class="profile">
    <div class="profile-header card">
      <div class="user-info">
        <el-avatar :size="80" :src="userInfo?.avatar">
          {{ userInfo?.username?.charAt(0) }}
        </el-avatar>
        <div class="user-details">
          <h2>{{ userInfo?.username }}</h2>
          <p>{{ userInfo?.email }}</p>
          <div class="user-stats">
            <span>帖子 {{ userInfo?.postsCount || 0 }}</span>
            <span>关注 {{ userInfo?.followingCount || 0 }}</span>
            <span>粉丝 {{ userInfo?.followersCount || 0 }}</span>
          </div>
        </div>
      </div>
      <div class="profile-actions">
        <el-button @click="showEditDialog">编辑资料</el-button>
        <el-button @click="showPasswordDialog">修改密码</el-button>
      </div>
    </div>

    <el-tabs v-model="activeTab" class="profile-tabs">
      <el-tab-pane label="我的帖子" name="posts">
        <div class="my-posts">
          <div v-if="posts.length === 0" class="empty-state">
            <el-empty description="还没有发布帖子">
              <el-button type="primary" @click="$router.push('/post/create')">
                发布第一篇帖子
              </el-button>
            </el-empty>
          </div>
          <div v-else class="post-list">
            <div v-for="post in posts" :key="post.id" class="post-item card">
              <h3 @click="goToPost(post.id)">{{ post.title }}</h3>
              <p>{{ post.content }}</p>
              <div class="post-meta">
                <span>{{ formatTime(post.createTime) }}</span>
                <span>{{ post.likesCount }} 点赞</span>
                <span>{{ post.commentsCount }} 评论</span>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="我的收藏" name="favorites">
        <div class="empty-state">
          <el-empty description="暂无收藏内容" />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 编辑资料对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑资料" width="500px">
      <el-form ref="editFormRef" :model="editForm" label-width="80px">
        <el-form-item label="头像">
          <el-upload
            action="/api/file/upload"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept="image/*"
          >
            <el-avatar :size="60" :src="editForm.avatar">
              {{ editForm.username?.charAt(0) }}
            </el-avatar>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" />
        </el-form-item>
        
        <el-form-item label="真实姓名">
          <el-input v-model="editForm.realName" />
        </el-form-item>
        
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleEditSubmit">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="80px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="passwordLoading" @click="handlePasswordSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 发布帖子按钮 -->
    <PostFab />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { updateUserInfo, changePassword } from '@/api/user'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import Cookies from 'js-cookie'
import PostFab from '@/components/PostFab.vue'

const router = useRouter()
const userStore = useUserStore()

const activeTab = ref('posts')
const posts = ref([])
const editDialogVisible = ref(false)
const passwordDialogVisible = ref(false)
const editLoading = ref(false)
const passwordLoading = ref(false)
const editFormRef = ref()
const passwordFormRef = ref()

// 用户信息
const userInfo = computed(() => userStore.userInfo)

// 编辑表单
const editForm = reactive({
  username: '',
  email: '',
  realName: '',
  phone: '',
  avatar: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 上传请求头
const uploadHeaders = {
  Authorization: `Bearer ${Cookies.get('token')}`
}

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 跳转到帖子详情
const goToPost = (id) => {
  router.push(`/post/${id}`)
}

// 显示编辑对话框
const showEditDialog = () => {
  Object.assign(editForm, userInfo.value)
  editDialogVisible.value = true
}

// 显示密码对话框
const showPasswordDialog = () => {
  Object.assign(passwordForm, {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  passwordDialogVisible.value = true
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像上传成功
const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    editForm.avatar = response.data.url
    ElMessage.success('头像上传成功')
  }
}

// 提交编辑
const handleEditSubmit = async () => {
  editLoading.value = true
  try {
    const response = await updateUserInfo(editForm)
    if (response.code === 200) {
      ElMessage.success('更新成功')
      editDialogVisible.value = false
      await userStore.fetchUserInfo()
    }
  } catch (error) {
    console.error('更新失败:', error)
  } finally {
    editLoading.value = false
  }
}

// 提交密码修改
const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    const response = await changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (response.code === 200) {
      ElMessage.success('密码修改成功')
      passwordDialogVisible.value = false
    }
  } catch (error) {
    console.error('密码修改失败:', error)
  } finally {
    passwordLoading.value = false
  }
}

// 获取我的帖子
const fetchMyPosts = async () => {
  try {
    // 模拟数据
    posts.value = [
      {
        id: 1,
        title: '我的校园生活分享',
        content: '今天天气很好，和同学们一起去图书馆学习...',
        createTime: '2024-01-01T10:00:00Z',
        likesCount: 10,
        commentsCount: 5
      }
    ]
  } catch (error) {
    console.error('获取帖子失败:', error)
  }
}

onMounted(() => {
  fetchMyPosts()
})
</script>

<style scoped>
.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30px;
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-details h2 {
  color: #303133;
  margin-bottom: 8px;
}

.user-details p {
  color: #909399;
  margin-bottom: 12px;
}

.user-stats {
  display: flex;
  gap: 24px;
  color: #606266;
  font-size: 14px;
}

.profile-actions {
  display: flex;
  gap: 12px;
}

.profile-tabs {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.post-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.post-item {
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.post-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.post-item h3 {
  color: #303133;
  margin-bottom: 8px;
  cursor: pointer;
}

.post-item h3:hover {
  color: #409eff;
}

.post-item p {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.post-meta {
  display: flex;
  gap: 16px;
  color: #909399;
  font-size: 12px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}
</style>